package com.example.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.demo.mapper.ProductMapper;
import com.example.demo.pojo.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ProductService {

    @Autowired
    ProductMapper productMapper;

    public List<Product> findAllProduct() {
        return productMapper.selectList(null);
    }


    public Product addProduct(Product product) {
        productMapper.insert(product);
        System.out.println("添加成功");

        return productMapper.selectById(product.getProduct_id());
    }

    public List<Product> findByClass(String product_class) {
        System.out.println("[DEBUG] 输入参数: " + product_class);
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_class", product_class);


        System.out.println("[SQL] " + queryWrapper.getTargetSql());

        return productMapper.selectList(queryWrapper);
    }

    public Product findById(Integer productId) {
        return productMapper.selectById(productId);
    }

    public List<Product> findByName(String productName) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("product_name", productName);
        return productMapper.selectList(queryWrapper);
    }

    public void deleteProduct(Integer productId) {
        productMapper.deleteById(productId);
        System.out.println("删除成功");
    }

    public Product updateProductPicture(Integer productId, String url) {
        UpdateWrapper<Product> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("product_id", productId);
        updateWrapper.set("product_picture", url);
        productMapper.update(null, updateWrapper);
        return productMapper.selectById(productId);
    }

    public List<Product> findByIdOrName(String productIdOrName) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("product_id", productIdOrName).like("product_name", productIdOrName);
        return productMapper.selectList(queryWrapper);
    }

    public Product ModifyProduct(Integer productId, String productName, float productPrice, Integer productStock, String productClass) {
        UpdateWrapper<Product> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("product_id", productId);
        updateWrapper.set("product_name", productName);
        updateWrapper.set("product_price", productPrice);
        updateWrapper.set("product_stock", productStock);
        updateWrapper.set("product_class", productClass);
        productMapper.update(null, updateWrapper);
        return productMapper.selectById(productId);
    }
}
